package blog.common.utils;

import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import java.io.UnsupportedEncodingException;
import java.util.Optional;

public class MailUtil {

    private JavaMailSender mailSender;

    private MailProperties mailProperties;

    public MailUtil(JavaMailSender mailSender, MailProperties mailProperties) {
        this.mailSender = mailSender;
        this.mailProperties = mailProperties;
    }


    public void send(String to,String subject,String content) throws MessagingException, UnsupportedEncodingException {
        // 创建⼀个邮件消息
        MimeMessage message = mailSender.createMimeMessage();
        // 创建 MimeMessageHelper
        MimeMessageHelper helper = new MimeMessageHelper(message, false);
        // 发件⼈邮箱和名称
        String personal = Optional.ofNullable(mailProperties.getProperties().get("personal"))
                .orElse(mailProperties.getUsername());
        helper.setFrom(mailProperties.getUsername(), personal);
        // 收件⼈邮箱
        helper.setTo(to);
        // 邮件标题
        helper.setSubject(subject);
        // 邮件正⽂，第⼆个参数表⽰是否是HTML正⽂
        helper.setText(content, true);
        // 发送
        mailSender.send(message);
    }
}
